#include "localchatserver.h"
#include "message.h"
#include <QDebug>

LocalChatServer::LocalChatServer(QObject *parent)
    : QLocalServer(parent)
{
    // 移除可能存在的旧服务器实例
    removeServer("LocalChatServer");
}

LocalChatServer::~LocalChatServer()
{
    stopServer();
}

bool LocalChatServer::startServer(const QString &serverName)
{
    if (listen(serverName)) {
        qDebug() << "本地聊天服务器已启动，名称:" << serverName;
        connect(this, &QLocalServer::newConnection, this, &LocalChatServer::onNewConnection);
        return true;
    } else {
        qDebug() << "服务器启动失败:" << errorString();
        return false;
    }
}

void LocalChatServer::stopServer()
{
    foreach (QLocalSocket *client, m_clients) {
        client->close();
        client->deleteLater();
    }
    m_clients.clear();
    m_clientNames.clear();
    close();
}

bool LocalChatServer::isServerRunning(const QString &serverName)
{
    QLocalSocket socket;
    socket.connectToServer(serverName);
    if (socket.waitForConnected(1000)) {
        socket.disconnectFromServer();
        return true;
    }
    return false;
}

void LocalChatServer::onNewConnection()
{
    QLocalSocket *clientSocket = nextPendingConnection();
    if (!clientSocket) return;
    
    qDebug() << "新客户端连接";
    
    connect(clientSocket, &QLocalSocket::readyRead, this, &LocalChatServer::onReadyRead);
    connect(clientSocket, &QLocalSocket::disconnected, this, &LocalChatServer::onDisconnected);
    connect(clientSocket, &QLocalSocket::disconnected, clientSocket, &QLocalSocket::deleteLater);
    
    m_clients.append(clientSocket);
    m_clientNames.append(""); // 临时占位，等待客户端发送用户名
}

void LocalChatServer::onReadyRead()
{
    QLocalSocket *clientSocket = qobject_cast<QLocalSocket*>(sender());
    if (!clientSocket) return;
    
    int clientIndex = getClientIndex(clientSocket);
    if (clientIndex == -1) return;
    
    QByteArray data = clientSocket->readAll();
    QString message = QString::fromUtf8(data).trimmed();
    
    // 第一个消息是用户名
    if (m_clientNames[clientIndex].isEmpty()) {
        m_clientNames[clientIndex] = message;
        QString username = message;
        emit newClientConnected(username);
        
        // 通知所有客户端有新用户加入
        Message joinMsg("系统", QString("%1 加入聊天").arg(username));
        broadcastMessage(joinMsg.toString(), clientSocket);
    } else {
        // 后续是聊天消息
        QString username = m_clientNames[clientIndex];
        emit messageReceived(username, message);
        
        // 封装成Message并广播给所有客户端
        Message msg(username, message);
        broadcastMessage(msg.toString());
    }
}

void LocalChatServer::onDisconnected()
{
    QLocalSocket *clientSocket = qobject_cast<QLocalSocket*>(sender());
    if (!clientSocket) return;
    
    int clientIndex = getClientIndex(clientSocket);
    if (clientIndex == -1) return;
    
    QString username = m_clientNames[clientIndex];
    emit clientDisconnected(username);
    
    // 通知其他客户端该用户离开
    if (!username.isEmpty()) {
        Message leaveMsg("系统", QString("%1 离开聊天").arg(username));
        broadcastMessage(leaveMsg.toString());
    }
    
    m_clients.removeAt(clientIndex);
    m_clientNames.removeAt(clientIndex);
    
    qDebug() << "客户端断开连接:" << username;
}

void LocalChatServer::broadcastMessage(const QString &message, QLocalSocket *exclude)
{
    QString data = message + "\n";
    foreach (QLocalSocket *client, m_clients) {
        if (client != exclude && client->state() == QLocalSocket::ConnectedState) {
            client->write(data.toUtf8());
        }
    }
}

int LocalChatServer::getClientIndex(QLocalSocket *socket)
{
    for (int i = 0; i < m_clients.size(); i++) {
        if (m_clients[i] == socket) {
            return i;
        }
    }
    return -1;
}